package com.ideal.hadoopadmin.web.controller.system.user;

import com.github.pagehelper.PageInfo;
import com.ideal.hadoopadmin.entity.main.User;
import com.ideal.hadoopadmin.entity.system.Role;
import com.ideal.hadoopadmin.entity.system.UserRole;
import com.ideal.hadoopadmin.entity.system.company.SystemCompany;
import com.ideal.hadoopadmin.framework.message.WebMessageLevel;
import com.ideal.hadoopadmin.framework.web.json.JsonObject;
import com.ideal.hadoopadmin.service.main.SystemUserService;
import com.ideal.hadoopadmin.service.system.RoleService;
import com.ideal.hadoopadmin.service.system.UserRoleService;
import com.ideal.hadoopadmin.service.system.company.SystemCompanyService;
import com.ideal.hadoopadmin.web.controller.UIController;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by fwj on 16-3-9.
 * 账户管理
 */
@Controller
@RequestMapping(UserManageController.PORTAL_PREFIX)
public class UserManageController extends UIController {
    Logger logger = LoggerFactory.getLogger(UserManageController.class);
    public final static String PORTAL_PREFIX = "/system/user";

    @Resource
    public SystemUserService systemUserService;
    @Resource
    public RoleService roleService;
    @Resource
    private SystemCompanyService systemCompanyService;
    @Resource
    private UserRoleService userRoleService;


    @RequestMapping("user_manage")
    public void index(HttpServletRequest request, Model model) {
        try {
            Map<String, Object> searchParams = WebUtils.getParametersStartingWith(request, "Q_");
            PageInfo page = systemUserService.queryUserList(searchParams, request);
            List<Role> roleList = roleService.queryRoleAllList();
            List<SystemCompany> customerList = systemCompanyService.queryClusterCompany();
            Collections.sort(customerList, new Comparator<SystemCompany>() {
                @Override
                public int compare(SystemCompany o1, SystemCompany o2) {
                    return o1.getCompanyName().compareTo(o2.getCompanyName());
                }
            });
            model.addAttribute("roleList", roleList);
            model.addAttribute("customerList", customerList);
            model.addAttribute("page", page);
            List<User> userList = page.getList();
            List<User> userListRole = new ArrayList<User>();
            for (int i = 0; i < userList.size(); i++) {
                User user = new User();
                user.setId(userList.get(i).getId());
                user.setUserName(userList.get(i).getUserName());
                user.setPhoneNumber(userList.get(i).getPhoneNumber());
                user.setCreateTime(userList.get(i).getCreateTime());
                user.setChangeTime(userList.get(i).getChangeTime());
                user.setEmail(userList.get(i).getEmail());
                user.setPassWord(userList.get(i).getPassWord());
                user.setRemark(userList.get(i).getRemark());
                user.setSystemCompany(userList.get(i).getSystemCompany());
                List<String> roleByUserId = userRoleService.queryUserRoleByUserId(userList.get(i).getId());
                user.setRole(roleByUserId.toString().replace("[", "").replace("]", ""));
                userListRole.add(user);
            }

            model.addAttribute("userListRole",userListRole);
            model.addAttribute("userName", searchParams.get("LIKE_su.userName"));

        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
    }

    @RequestMapping("edit_user_pop")
    public void edit(Model model, @RequestParam(value = "id", required = false) Long id) {
        List<SystemCompany> customerList = systemCompanyService.queryClusterCompany();
        Collections.sort(customerList, new Comparator<SystemCompany>() {
            @Override
            public int compare(SystemCompany o1, SystemCompany o2) {
                return o1.getCompanyName().compareTo(o2.getCompanyName());
            }
        });
        model.addAttribute("customerList", customerList);
        List<Role> roleList = roleService.queryRoleAllList();
        model.addAttribute("roleList", roleList);
        User userInfo = null;
        List<Long> queryRoleIdByUserId = new ArrayList<Long>();
        if (id != null) {
            userInfo = systemUserService.getUserById(id);
            queryRoleIdByUserId = userRoleService.queryRoleIdByUserId(id);
        }
        model.addAttribute("roleIds", queryRoleIdByUserId);
        model.addAttribute("userInfo", userInfo);
    }

    //
    @RequestMapping("save_user")
    @ResponseBody
    public JsonObject save(Model model, Long id,
                           @RequestParam(required = false) String login_name,
                           @RequestParam(required = false) String password,
                           @RequestParam(required = false) String name,
                           @RequestParam(required = false) Long sex,
                           @RequestParam(required = false) String mobile,
                           @RequestParam(required = false) String email,
                           @RequestParam(required = false) String role_id,
                           @RequestParam(required = false) Long customer_id,
                           @RequestParam(required = false) String job_title,
                           @RequestParam(required = false) String remark) {
        try {
            User user = new User();
            UserRole userRole = new UserRole();
            if (id != null) {
                user = systemUserService.getUserById(id);
                user.setUserName(name);
                user.setPhoneNumber(mobile);
                user.setEmail(email);
                user.setSystemCompanyId(customer_id);
                user.setRemark(remark);
                user.setChangeTime(new Date().getTime());
                systemUserService.updateUsers(user);
                //向用户角色表插入对应的记录
                userRoleService.deleteUserRoleByUserId(id);
                String[] roleIds = role_id.split(",");
                for (int i = 0; i < roleIds.length; i++) {
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(Long.parseLong(roleIds[i]));
                    userRoleService.saveUserRole(userRole);
                }
                return JsonObject.alert("修改成功!", WebMessageLevel.SUCCESS);
            } else {
                User userInfo = systemUserService.getUserByUserName(login_name);
                if (null != userInfo) {
                    return JsonObject.alert("用户名已存在！", WebMessageLevel.WARN);
                }
                user.setUserName(login_name);
                user.setPassWord(DigestUtils.md5Hex(password));
                user.setPhoneNumber(mobile);
                user.setEmail(email);
                user.setSystemCompanyId(customer_id);
                user.setRemark(remark);
                user.setCreateTime(new Date().getTime());
                user.setChangeTime(0L);
                systemUserService.saveUsers(user);
                //向用户角色表插入对应的记录
                String[] roleIds = role_id.split(",");
                for (int i = 0; i < roleIds.length; i++) {
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(Long.parseLong(roleIds[i]));
                    userRoleService.saveUserRole(userRole);
                }
                return JsonObject.alert("添加成功!", WebMessageLevel.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return JsonObject.error("新建/编辑失败!");
    }

    //
    @RequestMapping("delete_user")
    @ResponseBody
    public JsonObject delete(@RequestParam(value = "id") Long[] ids) {
        try {
            if (ids != null) {
                systemUserService.deleteUserById(ids);
                return JsonObject.alert("删除成功!",WebMessageLevel.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }

        return JsonObject.success();
    }

    //
//    @RequestMapping("check_user_pop")
//    public void checkUser(Model model, Long id){
//        User bean = securityServiceImp.getUser(id);
//        if(!new Long(0).equals(bean.getStatus())){
//            model.addAttribute("exist_check", 1);
//            model.addAttribute("mess", bean.getCheckMessage());
//            return;
//        }
//        model.addAttribute("bean", bean);
//    }
//
//    @RequestMapping("check_deal_user_pop")
//    @ResponseBody
//    public JsonObject checkDealChannel(Model model,
//                                       @RequestParam(value = "id", required = false) Long id,
//                                       @RequestParam(value = "checkStatus", required = false) Long checkStatus,
//                                       @RequestParam(value = "checkMessage", required = false) String checkMessage){
//        User user = securityServiceImp.getUser(id);
//        user.setStatus(checkStatus);
//        user.setCheckMessage(checkMessage);
//        user.setCheckTime(new Date());
//        securityServiceImp.saveUser(user);
//        return JsonObject.success();
//    }
//
    @RequestMapping("reset_password_pop")
    public void resetPassword(Model model, @RequestParam(value = "id", required = false) Long id) {
        User userInfo = null;
        if (id != null) {
            userInfo = systemUserService.getUserById(id);
        }
        model.addAttribute("userInfo", userInfo);
    }

    //
    @RequestMapping("reset_password")
    @ResponseBody
    public JsonObject reset(Model model, @RequestParam(value = "id") Long id,
                            @RequestParam(required = false) String password) {
        try {
            User user = systemUserService.getUserById(id);
            user.setPassWord(DigestUtils.md5Hex(password));
            systemUserService.updateUserPassword(user);
            return JsonObject.alert("密码修改成功!", WebMessageLevel.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return JsonObject.error("密码修改失败!");
    }


    @Override
    public String getPortalPrefix() {
        return PORTAL_PREFIX;
    }
}
